<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库"  >
              <el-input v-model="form.warehouseName" style="width:100%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" >
              <el-input v-model="form.shipmentName" style="width:100%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="供应商">
              <el-input v-model="form.supplierName" style="width:100%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple" >
            <el-form-item  label="来源单号" prop="sourceCode">
              <el-select v-model="form.sourceCode" placeholder="请输入来源单号  " style="width:100%" disabled>
                <el-option
                  v-for="item in sourceData"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                />
              </el-select>

            </el-form-item>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="grid-content bg-purple" >
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:100%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-toolbar id="toolbar_demo3">
      <template v-slot:buttons>
        <el-button @click="funcAddItem" type="primary" plain size="small">选择退货商品</el-button>
      </template>
    </vxe-toolbar>
    <vxe-modal v-model="modelAddFlag" title="选择退货商品" width="1300" height="800" resize>
      <compItmeAdd ref="addRef" @fatherAddMethod="fatherAddItem"/>
    </vxe-modal>

    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      :footer-method="footerMethod"

      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称" width="270"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码" ></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"></vxe-table-column>
      <vxe-table-column field="canReturnQuantity" title="可退数量"></vxe-table-column>
      <vxe-table-column field="quantity" title="退货数量" :edit-render="{name: 'input'}" ></vxe-table-column>
      <vxe-table-column field="remarks" title="备注" ></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="50">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="$refs.xTable.remove(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import request from '@/utils/request'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import { validatePhone, validateIDNumber } from "@/utils/validate.js";
import supplierSelect from '@/views/components/supplierElSelect.vue'
import {getWarehouse} from '@/api/basicInfo'
import compItmeAdd from './components/item.vue'
import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
import warehouseSelect from '@/views/components/warehouseSelect.vue'
import { goodsUnitConversion, refundSubmit ,refundLocalSave, getSources,refundDetail} from '@/api/outStorage'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
export default {
  name: 'Parent',
  components: {
    supplierSelect,
    compItmeAdd,
    warehouseSelect,
    shipmentSelect3,
  },
  data() {
    return {
      allAlign:'center',
      warehouseData:[],
      modelAddFlag: false,
      itemData: [],
      sourceData:[],
      units:[],
      isDisable:false,   //确定键显示按钮
      form: {
        shipmentCode: '',
        type:'1',
        customerCode:'',
        warehouseCode:"",
        sourceCode:'',
        supplierCode:'',
        remarks: '', // 备注
        gmtPlanArrival: '',
        deliveryItemList: []
      },
      loading: false,
      tableData: [
      ],
      rules: {
        shipmentCode: [
          { required: true, message: '请选择入驻商', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        customerCode: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        sourceCode: [
          { required: true, message: '请选择来源单号', trigger: 'change' }
        ],
      },
      validRules: {
        goodsName: [
          { required: true, message: '商品名称必须填写' },
        ],
        unitCode: [
          { required: true, message: '单位必须填写' },
        ],
        quantity: [
          { required: true, message: '数量必须填写' },
          { pattern: /^[1-9]+[0-9]*$/, message: '数量必须大于0' },
          { max: 20, message: '数量不能超过20位'}
        ],
      },
      listQuery: {
        page: 1,
        limit: 13,
        totalzong: 0
      },
    }
  },
  // watch: {
  //   'form.sourceCode': {
  //     handler () {
  //       this.tableData = []
  //     },
  //     deep: true
  //   },

  // },

  created() {
    this.getInfo();
  },
  methods: {
    // 获取页面信息
    getInfo() {
      this.loading = true
      let code = this.$route.query.code ? this.$route.query.code : "";
      refundDetail(code).then(response => {
        this.form = response.data,
        this.tableData = this.form.deliveryItemVOList

        this.loading = false
      }).then(()=>{
        this.getSourceList();
      });

    },


    //选择供应商
    setsupplierCode(value){
      this.form.supplierCode = value.code;
      this.tableData = [];
      this.form.sourceCode = '';
      this.getSourceList();
    },
    // 选择入驻商
    setShipmentInfo(info) {
      this.form.shipmentCode = info.code;
      this.form.shipmentName = info.name;
      this.tableData = [];
      this.form.sourceCode = '';
      this.getSourceList();
    },
    // 选择仓库
    setWarehouseCode(value){
      this.form.warehouseCode = value;
      this.tableData = [];
      this.form.sourceCode = '';
      this.getSourceList();
    },

    // 添加方法
    funcAddItem() {
      if (this.form.sourceCode) {
        this.$refs.addRef.getInfo(this.form.sourceCode)
        this.modelAddFlag = true
      } else {
        this.$message.error('来源单号不可为空')
      }

    },
    // 增加组件的父方法
    fatherAddItem(item) {
      this.tableData = item
      this.modelAddFlag = false
      // this.insertEvent()
    },
    // 新增
    insertEvent(row) {
      this.$refs.xTable.insertAt(this.itemData, row)
    },

    //仓库、来源查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
      })
    },

    // 获取订单列表
    getSourceList(){
      let params = {
        warehouseCode: this.form.warehouseCode,
        shipmentCode: this.form.shipmentCode,
        supplierCode: this.form.supplierCode,
      };
      getSources(params).then(response => {
        this.sourceData = response.data
      })
    },
    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }
          if (['canReturnQuantity','quantity'].includes(column.property)) {
              return XEUtils.sum(data, column.property).toFixed(3)
          }
          return '-'
        })
      ]
    },

    // 提交
    funcSubmitCheck() {
      this.form.deliveryItemList = this.$refs.xTable.tableData
      let a = ''
      this.form.deliveryItemList.forEach( i => {
        if(i.quantity == null || i.quantity <= 0){
          a = 0
          return
        }
        if(i.quantity > i.canReturnQuantity || i.quantity < 0 ){
          this.$message.error('退货数量不可大于可退数量')
          a =1
          return
        }else{
          a = 0
        }
      })
      const data = this.form
      if (!this.$refs.xTable.tableData.length) {
        this.$message.error('请选择退货商品')
      } else {

        if(a == 0){
          this.$refs['form'].validate((valid) => {
            if (valid) {
            const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
            this.$refs.xTable.validate((valids) => {
              if(valids){

              this.isDisable = true
              refundSubmit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.isDisable = false
              }).then(() => {
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: "/wms/delivery"
                });
              }).catch(() => this.isDisable = false)
              }            })

            }
          })
        }
      }
    },
    // 保存
    funcSubmitSave() {
      this.form.deliveryItemList = this.$refs.xTable.tableData
      let a = ''
      this.form.deliveryItemList.forEach( i => {
        if(i.quantity == null || i.quantity <= 0){
          a = 0
          return
        }
        if(i.quantity > i.canReturnQuantity || i.quantity < 0 ){
          this.$message.error('退货数量不可大于可退数量')
          a =1
          return
        }else a = 0
      })
      const data = this.form
      if (!this.$refs.xTable.tableData.length) {
        this.$message.error('请选择退货商品')
      } else {


      if(a == 0){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
            this.$refs.xTable.validate((valids) => {
              if(valids){

            this.isDisable = true
            refundLocalSave(data).then(response => {
              this.$message({ message: response.msg, type: 'success' })
              this.isDisable = false
            }).then(() => {
              this.$eventBus.$emit('refreshList')
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.push({
                path: "/wms/delivery"
              });
            }).catch(() => this.isDisable = false)
                          }            })

          }
        })
      }
      }
    },

    // 取消
    funcCancel() {
      this.$emit('fatherCancelMethod', 'add')
    },
  }
}
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 175px;
    // float: right;
  }
  </style>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
